package me.khrystal.rxnews.module.photo.ui;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import android.widget.ViewAnimator;

import com.socks.library.KLog;

import io.vov.vitamio.utils.StringUtils;
import me.khrystal.rxnews.R;
import me.khrystal.rxnews.annotation.ActivityFragmentInject;
import me.khrystal.rxnews.base.BaseActivity;
import me.khrystal.rxnews.bean.SinaPhotoDetail;
import me.khrystal.rxnews.module.photo.presenter.IPhotoDetailPresenter;
import me.khrystal.rxnews.module.photo.presenter.IPhotoDetailPresenterImpl;
import me.khrystal.rxnews.module.photo.ui.adapter.OnPageChangeListenerAdapter;
import me.khrystal.rxnews.module.photo.ui.adapter.PhotoAdapter;
import me.khrystal.rxnews.module.photo.view.IPhotoDetailView;
import me.khrystal.rxnews.utils.MeasureUtil;
import me.khrystal.rxnews.widget.HackyViewPager;
import me.khrystal.rxnews.widget.ThreePointLoadingView;
import zhou.widget.RichText;

/**
 * usage:
 * author: kHRYSTAL
 * create time: 16/4/29
 * update time:
 * email: 723526676@qq.com
 */
@ActivityFragmentInject(contentViewId = R.layout.activity_photo_detail,
    enableSlidr = true,
    menuId =  R.menu.menu_settings,
    toolbarTitle = R.string.photo_detail)
public class PhotoDetailActivity extends BaseActivity<IPhotoDetailPresenter>
    implements IPhotoDetailView{

    private ThreePointLoadingView mLoadingView;
    private HackyViewPager mViewPager;
    private TextView mTitleTv;
    private TextView mPageTv;
    private RichText mContentTv;
    private int mTitleTvPaddingTop;
    private int mContentTvPaddingBottom;
    private int mOffset;
    private ValueAnimator mAnimator;
    private int mContentTvWidth;
    private int mPageTvWidth;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAnimator != null && mAnimator.isRunning()){
            mAnimator.removeAllUpdateListeners();
            mAnimator.cancel();
        }
    }

    @Override
    protected void initView() {
        mLoadingView = (ThreePointLoadingView)findViewById(R.id.tpl_view);
        mLoadingView.setOnClickListener(this);

        mViewPager = (HackyViewPager)findViewById(R.id.viewpager);
        mTitleTv = (TextView) findViewById(R.id.tv_photo_detail_title);
        mPageTv = (TextView)findViewById(R.id.tv_photo_detail_page);
        mContentTv = (RichText)findViewById(R.id.tv_photo_detail_content);

        String photoId = getIntent().getStringExtra("photoId");

        SinaPhotoDetail data = (SinaPhotoDetail)getIntent().getSerializableExtra("neteast");
        mPresenter = new IPhotoDetailPresenterImpl(this,photoId,data);

    }

    @Override
    public void initViewPager(final SinaPhotoDetail photoList) {

        mOffset = MeasureUtil.getScreenSize(this).y / 4;

        mTitleTv.setText(photoList.data.title);
        mTitleTv.setTag(true);

        final PhotoAdapter photoAdapter = new PhotoAdapter(this,photoList.data.pics);
        mViewPager.setAdapter(photoAdapter);

        final OnPageChangeListenerAdapter mPageChangeListenerAdapter = new OnPageChangeListenerAdapter() {
            @Override
            public void onPageSelected(int position) {
                if (position == 0 && mSlidrInterface != null){
                    mSlidrInterface.unlock();
                } else if (mSlidrInterface != null) {
                    mSlidrInterface.lock();
                }

                final String s = getString(R.string.photo_page,position + 1,
                        photoList.data.pics.size());

                mPageTv.setText(s);

                final String alt = photoList.data.pics.get(position).alt;
                if (!TextUtils.isEmpty(alt) && !alt.equals(mContentTv.getText().toString().trim())){
                    ObjectAnimator.ofFloat(mContentTv,"alpha",0.5f,1).setDuration(500).start();
                    mContentTv.setRichText(getString(R.string.photo_detail_content, alt));
                    dynamicSetTextViewGravity();
                }

                // 每次切换回来都要处理一下，因为切换回来当前的图片不会调用OnPhotoExpandListener的onExpand方法
                controlView(photoAdapter.getPics().get(position).showTitle);
            }
        };

        mViewPager.addOnPageChangeListener(mPageChangeListenerAdapter);
        mContentTv.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
                    @Override
                    public void onGlobalLayout() {
                        mPageTvWidth = mPageTv.getMeasuredWidth();
                        mContentTvWidth = mContentTv.getMeasuredWidth();
                        KLog.e("长度："+ mPageTvWidth + ";" + mContentTvWidth);
                        mPageChangeListenerAdapter.onPageSelected(0);
                        mContentTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                });
        photoAdapter.setOnPhotoExpandListener(new PhotoAdapter.OnPhotoExpandListener() {
            @Override
            public void onExpand(boolean show, int position) {
                if (mViewPager.getCurrentItem() == position)
                    controlView(show);
            }
        });
    }

    /**
     *
     * @param showTitle 当前是否已经显示
     *                  false 需要隐藏
     *                  true 需要显示
     */
    private void controlView(boolean showTitle) {
        if (mAnimator != null && mAnimator.isRunning()){
            return;
        }
        mAnimator = new ValueAnimator();
        if (!showTitle && (boolean)mContentTv.getTag()){
            //隐藏
            mAnimator.setIntValues(0,mOffset);
            mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    //隐藏
                    mAnimator.setIntValues(0,mOffset);
                    mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            mTitleTv.setTag(false);
                            mTitleTv.setPadding(mTitleTv.getPaddingLeft(),
                                    -(int)animation.getAnimatedValue(),mTitleTv.getPaddingRight(),
                                    mTitleTv.getPaddingBottom());
                            mContentTv.setPadding(mContentTv.getPaddingLeft(),mContentTv.getPaddingTop(),
                                    mContentTv.getPaddingRight(),-(int)animation.getAnimatedValue());
                            ViewCompat.setScaleX(mPageTv, 1 - animation.getAnimatedFraction());
                            ViewCompat.setScaleY(mPageTv, 1 - animation.getAnimatedFraction());

                        }
                    });

                }
            });
        }else if (showTitle && !(boolean)mTitleTv.getTag()){
            //显示
            mAnimator = new ValueAnimator();
            mAnimator.setIntValues(mOffset,0);
            mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    mTitleTv.setTag(true);
                    mTitleTv.setPadding(mTitleTv.getPaddingLeft(),
                            -(int)animation.getAnimatedValue() + mTitleTvPaddingTop,
                            mTitleTv.getPaddingRight(),mTitleTv.getPaddingBottom());
                    mContentTv.setPadding(mContentTv.getPaddingLeft(),mContentTv.getPaddingTop(),
                            mContentTv.getPaddingRight(),-(int)animation.getAnimatedValue() + mContentTvPaddingBottom);
                    ViewCompat.setScaleX(mPageTv,animation.getAnimatedFraction());
                    ViewCompat.setScaleY(mPageTv,animation.getAnimatedFraction());
                }
            });
        }else
            return;
        mAnimator.setDuration(300);
        mAnimator.start();
    }

    private void dynamicSetTextViewGravity() {
        if ((mContentTv.getPaint()
                .measureText(mContentTv.getText().toString()) < mContentTvWidth)) {
            mContentTv.setGravity(Gravity.CENTER);
            // 设为中心对齐，去掉前面两个空格
            mContentTv.setRichText(StringUtils.replaceBlank(mContentTv.getText().toString()));
            KLog.e("设为中心对齐，去掉前面两个空格");
        } else {
            mContentTv.setGravity(Gravity.TOP | Gravity.START);
            KLog.e("设为原始对齐");
        }
    }

    /**
     * 当Activity渲染完毕 即用户可进行界面操作时回调此方法
     * entry: onStart---->onResume---->onAttachedToWindow----------->onWindowVisibilityChanged--visibility=0---------->onWindowFocusChanged(true)------->

      exit:  onPause---->onStop---->onWindowFocusChanged(false)  ---------------------- (lockscreen)

     exit : onPause----->onWindowFocusChanged(false)-------->onWindowVisibilityChanged--visibility=8------------>onStop(to another activity)
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && mTitleTvPaddingTop == 0){
            mTitleTvPaddingTop = mTitleTv.getPaddingTop();
            mContentTvPaddingBottom = mContentTv.getPaddingBottom();
        }
    }

    @Override
    public void showProgress() {
        mLoadingView.play();
    }

    @Override
    public void hideProgress() {
        mLoadingView.stop();
    }
}
